package cn.zhou.jin.service.impl;

import cn.zhou.basic.service.impl.BaseServiceImpl;
import cn.zhou.jin.domain.Department;
import cn.zhou.jin.mapper.DepartmentMapper;
import cn.zhou.jin.service.IDepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Transactional (readOnly = true,propagation = Propagation.SUPPORTS)
public class DepartmentServiceImpl extends BaseServiceImpl<Department> implements IDepartmentService {
    @Autowired
    private DepartmentMapper departmentMapper;

    @Override
    public List<Department> queryTree(){
        // 这个是拿到所有的数据
        List<Department> departments = departmentMapper.loadAll();
        // 创建一个map 对象来装
        Map<Long,Department> allDepts= new HashMap<>();
        // 遍历一下    把拿到数据装进 map
        for (Department department:departments){
            allDepts.put(department.getId(),department);
        }
        // 创建一个数组
       List<Department> firstDepts = new ArrayList<>();
        for(Department tmp:departments){
            //遍历 把如果里面的数组的parent id 是空 那么就是祖宗 单独提出来
            if(tmp.getParent_id()==null){
                // 添加到数组中去
                firstDepts.add(tmp);
            }else {
                // 不是祖宗，那么就是儿子 把自己当成儿子去找爹    即 prent id 有值
                Department parent=allDepts.get(tmp.getParent_id());
                if (parent!=null){
                    parent.getChildren().add(tmp);

                }
            }
        }
        return firstDepts;

    }
}